<template>
  <div id="layout">
    <websocket v-if="role == 2" />
    <div v-if="logouturl" class="my-iframe">
      <iframe
        allow="fullscreen"
        referrerpolicy="no-referrer-when-downgrade"
        sandbox="allow-same-origin allow-scripts allow-forms"
        :src="logouturl"
        width="100%"
      ></iframe>
      <!-- src="http://112.103.254.249:21146/gitea/test" -->
    </div>
    <div class="app-wrap">
      <div class="top">
        <div class="top-box">
          <div class="logo">
            <!-- <img src="@/assets/img/logo.png" /> -->
            <div>数字人业务情景培训系统</div>
          </div>
          <el-menu
            router
            mode="horizontal"
            :default-active="$route.meta.topMenu"
            class="top-nav"
          >
            <el-menu-item index="/">任务管理</el-menu-item>
            <el-menu-item index="/roleMake">角色制作</el-menu-item>
            <el-menu-item index="/sceneMake">情景制作</el-menu-item>
            <el-menu-item index="/institutionManage">机构管理</el-menu-item>
            <el-menu-item index="/personManage">人员管理</el-menu-item>
          </el-menu>
          <div class="username">
            <div style="height: 30px"><img src="@/assets/img/face0.png" /></div>
            <div v-if="userInfo && userInfo.name">
              你好，{{ userInfo.name }}
            </div>
            <div class="pwd" @click="showDialog">
              <img src="@/assets/img/pwd.png" />
              修改密码
            </div>
            <div class="logout" @click="handleLogout">退出登录</div>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="l-left scroll-container">
          <el-menu
            :default-active="$route.meta.navId"
            :default-openeds="defaultOpeneds"
            class="nav-menu"
            @select="handleMenuSelect"
            router
            :unique-opened="true"
          >
            <!-- <el-menu-item
              v-if="
                !userInfo ||
                !userInfo.roles ||
                userInfo.roles[0] !== 'student' ||
                ['home'].includes('home')
              "
              index="home"
            >
              <div class="nav-item" :class="{ active: isActive('home') }">
                <div class="nav-icon">
                  <img src="/nav/1.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/1-active.png" />
                </div>
                <div class="nav-txt">系统控制台</div>
              </div>
            </el-menu-item> -->
            <el-sub-menu
              v-if="
                !userInfo || !userInfo.roles || userInfo.roles[0] !== 'student'
              "
              index="zonghe"
            >
              <template #title>
                <div class="nav-item" :class="{ active: isActive('zonghe') }">
                  <div class="nav-icon">
                    <img src="/nav/2.png" />
                  </div>
                  <div class="nav-icon-active">
                    <img src="/nav/2-active.png" />
                  </div>
                  <div class="nav-txt">综合能力评定</div>
                </div>
              </template>
              <el-menu-item v-if="role == 7" index="/zonghe/zongheping">
                <div
                  class="nav-item"
                  :class="{ active: isActive('zonghe-ping') }"
                >
                  <div class="nav-txt">综合能力评定</div>
                </div>
              </el-menu-item>
              <el-menu-item v-if="role == 7" index="/zonghe/zonghebiye">
                <div
                  class="nav-item"
                  :class="{ active: isActive('zonghe-biye') }"
                >
                  <div class="nav-txt">目标/要求设定</div>
                </div>
              </el-menu-item>
              <el-menu-item index="/zonghe/zonghelist">
                <div
                  class="nav-item"
                  :class="{ active: isActive('zonghe-list') }"
                >
                  <div class="nav-txt">课程达成度</div>
                </div>
              </el-menu-item>
            </el-sub-menu>

            <el-menu-item
              v-if="!userInfo || !userInfo.roles || userInfo.roles[0]"
              index="gongcheng"
            >
              <div class="nav-item" :class="{ active: isActive('gongcheng') }">
                <div class="nav-icon">
                  <img src="/nav/3.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/3-active.png" />
                </div>
                <div class="nav-txt">工程实践项目管理</div>
              </div>
            </el-menu-item>

            <el-sub-menu
              v-if="
                !userInfo || !userInfo.roles || userInfo.roles[0] !== 'student'
              "
              index="aiTeaching"
            >
              <template #title>
                <div
                  class="nav-item"
                  :class="{ active: isActive('aiTeaching') }"
                >
                  <div class="nav-icon">
                    <img src="/nav/4.png" />
                  </div>
                  <div class="nav-icon-active">
                    <img src="/nav/4-active.png" />
                  </div>
                  <div class="nav-txt">AI教学</div>
                </div>
              </template>
              <el-menu-item index="/aiTeaching/courseSystem">
                <div
                  class="nav-item"
                  :class="{ active: isActive('course-system') }"
                >
                  <div class="nav-txt">课程体系</div>
                </div>
              </el-menu-item>
              <el-menu-item index="/aiTeaching/courseBuild">
                <div
                  class="nav-item"
                  :class="{ active: isActive('course-build') }"
                >
                  <div class="nav-txt">课程构建</div>
                </div>
              </el-menu-item>
            </el-sub-menu>

            <el-menu-item
              v-if="
                !userInfo || !userInfo.roles || userInfo.roles[0] == 'student'
              "
              index="/aiStuding/stuListCourseSystem"
            >
              <div class="nav-item" :class="{ active: isActive('aiStuding') }">
                <div class="nav-icon">
                  <img src="/nav/4.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/4-active.png" />
                </div>
                <div class="nav-txt">AI学伴</div>
              </div>
            </el-menu-item>

            <!-- <el-menu-item
              v-if="
                !userInfo || !userInfo.roles || userInfo.roles[0] !== 'student'
              "
              index="xueke"
            >
              <div class="nav-item" :class="{ active: isActive('xueke') }">
                <div class="nav-icon">
                  <img src="/nav/5.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/5-active.png" />
                </div>
                <div class="nav-txt">学科知识库</div>
              </div>
            </el-menu-item> -->

            <!-- <el-menu-item
              v-if="
                !userInfo ||
                !userInfo.roles ||
                userInfo.roles[0] !== 'student' ||
                ['zhishi'].includes('zhishi')
              "
              index="zhishi"
            >
              <div
                class="nav-item"
                :class="{ active: isActive('zhishi') }"
              >
                <div class="nav-icon">
                  <img src="/nav/6.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/6-active.png" />
                </div>
                <div class="nav-txt">知识图谱</div>
              </div>
            </el-menu-item> -->

            <el-menu-item
              v-if="
                !userInfo ||
                !userInfo.roles ||
                userInfo.roles[0] !== 'student' ||
                ['zhinengti'].includes('zhinengti')
              "
              index="zhinengti"
            >
              <div class="nav-item" :class="{ active: isActive('zhinengti') }">
                <div class="nav-icon">
                  <img src="/nav/7.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/7-active.png" />
                </div>
                <div class="nav-txt">大模型广场</div>
              </div>
            </el-menu-item>

            <el-menu-item
              v-if="
                !userInfo || !userInfo.roles || userInfo.roles[0] !== 'student'
              "
              index="shuziren"
            >
              <div class="nav-item" :class="{ active: isActive('shuziren') }">
                <div class="nav-icon">
                  <img src="/nav/8.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/8-active.png" />
                </div>
                <div class="nav-txt">数字教师资产库</div>
              </div>
            </el-menu-item>

            <el-menu-item v-if="role == 7" index="user">
              <div class="nav-item" :class="{ active: isActive('user') }">
                <div class="nav-icon">
                  <img src="/nav/9.png" />
                </div>
                <div class="nav-icon-active">
                  <img src="/nav/9-active.png" />
                </div>
                <div class="nav-txt">用户管理</div>
              </div>
            </el-menu-item>
          </el-menu>
        </div>
        <div ref="right" class="l-right">
          <router-view></router-view>
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" width="630" :before-close="handleClose">
      <div class="my-dialog">
        <div class="my-dialog-content">
          <div>
            <div class="item-label"><span class="red">*</span>原密码：</div>
            <div class="item-content">
              <el-input
                v-model="pwdForm.oldPassword"
                type="password"
                autocomplete="new-password"
              ></el-input>
            </div>
          </div>
          <div>
            <div class="item-label"><span class="red">*</span>新密码：</div>
            <div class="item-content">
              <el-input
                v-model="pwdForm.newPassword"
                type="password"
                autocomplete="new-password"
              ></el-input>
            </div>
          </div>
          <div>
            <div class="item-label"><span class="red">*</span>确认密码：</div>
            <div class="item-content">
              <el-input
                v-model="pwdForm.confirmPassword"
                type="password"
                autocomplete="new-password"
              ></el-input>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="editPassword"> 确定 </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import websocket from "../components/websocket.vue";

export default {
  components: {
    websocket,
  },
  name: "App",
  data() {
    return {
      dialogVisible: false,
      logouturl: "",
      defaultOpeneds: [],
      isShowSocket: false, // 是否显示socket连接框
      //role 1普通教师 2学生 7超级教师
      role: 0,
      roles: "",
      teaNavList: [
        {
          navId: "home",
          icon: "/nav/1.png",
          activeIcon: "/nav/1-active.png",
          text: "系统控制台",
          url: "/",
        },
        {
          navId: "zonghe",
          icon: "/nav/2.png",
          activeIcon: "/nav/2-active.png",
          text: "综合能力评定",
          url: "/zonghe",
        },
        {
          navId: "gongcheng",
          icon: "/nav/3.png",
          activeIcon: "/nav/3-active.png",
          text: "工程实践项目管理",
          url: "/gongcheng",
        },
        {
          navId: "ai",
          icon: "/nav/4.png",
          activeIcon: "/nav/4-active.png",
          text: "AI智能分析",
          url: "/ai",
        },
        {
          navId: "xueke",
          icon: "/nav/5.png",
          activeIcon: "/nav/5-active.png",
          text: "学科知识库",
          url: "/xueke",
        },
        {
          navId: "zhishi",
          icon: "/nav/6.png",
          activeIcon: "/nav/6-active.png",
          text: "知识图谱",
          url: "/zhishi",
        },
        {
          navId: "zhinengti",
          icon: "/nav/7.png",
          activeIcon: "/nav/7-active.png",
          text: "大模型智能体",
          url: "/zhinengti",
        },
        {
          navId: "shuziren",
          icon: "/nav/8.png",
          activeIcon: "/nav/8-active.png",
          text: "数字人构建",
          url: "/shuziren",
        },
        {
          navId: "user",
          icon: "/nav/9.png",
          activeIcon: "/nav/9-active.png",
          text: "用户管理",
          url: "/user",
        },
        // {
        //   icon: "/nav/9.png",
        //   activeIcon: "/nav/9-active.png",
        //   text: "对话",
        //   url: "/agent",
        // },
      ],
      activeIndex: null, // 当前激活的导航项索引
      userInfo: null, // 用户信息
      pwdForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
    };
  },
  watch: {
    "$route.meta.navId": function (newNavId) {
      console.log("Route changed, new navId:", newNavId);
      this.updateActiveIndex(newNavId);
    },
  },
  computed: {
    filteredNavList() {
      if (this.userInfo && this.userInfo.roles) {
        const roles = this.userInfo.roles[0];

        // 学生角色的可见导航项
        const studentNavIds = ["home", "zhishi", "zhinengti"];

        return this.teaNavList.filter((item) => {
          // 如果是学生，只显示 studentNavIds 中的导航项
          if (roles === "student") {
            return studentNavIds.includes(item.navId);
          }

          // 如果是教师，显示所有导航项
          return true;
        });
      }

      // 如果没有用户信息或角色，返回空列表
      return [];
    },
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem("userInfo")) || {};
    //role 1普通教师 2学生 7超级教师
    this.role = this.userInfo.role;
    if (this.role) {
      this.updateActiveIndex(this.$route.meta.navId);
      this.initializeWebSocket();
      this.setDefaultOpeneds();
    } else {
      this.$router.push("/login");
    }
    this.getLoginPage();
  },
  methods: {
    showDialog() {
      this.clearForm();
      this.dialogVisible = true;
    },
    editPassword() {
      if (this.pwdForm.oldPassword === "") {
        this.$message.error("原密码不能为空");
        return;
      }
      if (this.pwdForm.newPassword !== this.pwdForm.confirmPassword) {
        this.$message.error("两次密码输入不一致，请重新输入");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "修改中，请稍后...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const url = `/tes/user/password`;
      const params = this.pwdForm;
      this.$axios
        .put(url, params)
        .then((response) => {
          const res = response;
          this.$message.success(res.message || "修改密码成功");
          this.dialogVisible = false;
          this.handleLogout();
        })
        .finally(() => {
          loading.close();
        });
    },
    clearForm() {
      this.pwdForm.oldPassword = "";
      this.pwdForm.newPassword = "";
      this.pwdForm.confirmPassword = "";
    },
    handleClose() {
      this.dialogVisible = false;
    },
    getLoginPage() {
      const url = `/tes/project/gitea-url`;
      this.$axios
        .get(url)
        .then((response) => {
          const res = response.data;
          const { gitBackUrl } = res;
          //http://112.103.254.249:21146/gitea/auto-logout
          this.logouturl = `${gitBackUrl}/auto-logout`;
          console.log("layoutlogout");
        })
        .finally(() => {});
    },
    setDefaultOpeneds() {
      const path = this.$route.path;

      if (path.startsWith("/zonghe")) {
        this.defaultOpeneds = ["zonghe"];
      } else if (path.startsWith("/aiTeaching")) {
        this.defaultOpeneds = ["aiTeaching"];
      } else {
        this.defaultOpeneds = [];
      }
    },
    initializeWebSocket() {
      if (this.userInfo === null) {
        return;
      }
      const userId = this.userInfo.userId; // 获取用户 ID
      const roles = this.userInfo.roles[0]; // 获取用户角色
      if (roles !== "student") {
        return;
      }
      if (!userId) {
        console.error("用户 ID 不存在，无法初始化 WebSocket");
        return;
      }
      // 动态更新 WebSocket URL
      const websocketUrl = `/tes/ws/assess/${userId}`;
      // const websocketUrl = `/tes/ws/assess/150`;
      // console.log(this.$websocket, 445566);
      this.$websocket.state.manager.close();
      this.$websocket.state.manager.url = websocketUrl;

      // 初始化 WebSocket 连接
      this.$websocket.state.manager.connect();
    },
    isActive(navId) {
      return this.$route.matched.some((route) => {
        return (
          route.name === navId || (route.meta && route.meta.navId === navId)
        );
      });
    },
    checkUserRole() {
      if (this.userInfo && this.userInfo.roles) {
        this.roles = this.userInfo.roles[0];
        const roles = this.userInfo.roles[0];
        if (roles === "student") {
          this.isShowSocket = true;
        } else if (roles === "teacher") {
          // 教师逻辑
        } else {
          // 其他角色逻辑
        }
      }
    },
    updateActiveIndex(navId) {
      this.teaNavList.forEach((item, index) => {
        if (item.navId === navId) {
          this.activeIndex = index;
        }
      });
    },
    handleMenuSelect(index) {
      const item = this.teaNavList.find((nav) => nav.navId === index);
      if (item) {
        this.$refs.right.scrollTop = 0;
        this.$router.push(item.url);
      }
    },
    handleLogout() {
      this.logout();
    },
    logout() {
      let url = "/tes/logout";
      this.$axios.post(url).then((response) => {
        // 清除 localStorage 中的 token 和 userinfo
        this.$store.commit("logout");
        localStorage.removeItem("userInfo");
        const res = response;
        this.$message.success(res.msg || "退出登录成功");
        this.$router.push("/login");
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.my-dialog {
  .my-dialog-title {
    padding: 0 48px;
    font-size: 20px;
    color: #204077;
    margin-bottom: 35px;
  }

  .dialog-info {
    font-size: 16px;
    color: #333333;
    line-height: 29px;
    padding: 40px 50px;
  }

  .my-dialog-tab {
    display: flex;
    justify-content: center;
    gap: 55px;

    .disabled {
      cursor: no-drop;
      color: #a8abb2;

      &:hover {
        color: #a8abb2;
      }
    }

    > div {
      font-size: 16px;
      color: #6b6a85;
      cursor: pointer;

      &:hover {
        color: #457aff;
      }

      &.active {
        color: #457aff;
        cursor: pointer;

        &:hover {
          color: #457aff;
        }

        &::after {
          content: "";
          display: block;
          width: 50%;
          height: 2px;
          margin: 17px auto 0;
          background: #3486e4;
        }
      }
    }
  }

  .my-dialog-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 20px 0 40px;

    > div {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 24px;

      &.flex-start {
        align-items: flex-start;
      }

      .item-label {
        width: 100px;
        text-align: right;
        font-size: 16px;
        color: #000000;

        .red {
          color: red;
          margin-right: 4px;
        }
      }

      .item-content {
        .tiao-box {
          width: 400px;
          display: flex;
          gap: 30px;

          > a {
            width: 120px;
            height: 60px;
            border-radius: 10px;
            background: #ecf3ff;
            display: flex;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
            cursor: pointer;

            &:hover {
              background: #ecf1fa;
              border: 2px solid #457aff;
            }
          }
        }

        :deep(.el-input) {
          width: 400px;
        }

        :deep(.el-textarea) {
          width: 400px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
#layout {
  background: #f9fafb;
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;

  .my-iframe {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }

  .app-wrap {
    // overflow: hidden;
  }

  .top {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background: #000000;
    padding: 0 44px 0 26px;

    .top-box {
      width: 1200px;
      height: 80px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .top-nav {
        padding-left: 80px;
        flex: 1;
        display: flex;
        align-items: center;
        gap: 20px;
        background: transparent;
        border-bottom: none;

        .el-menu-item {
          position: relative;
          font-size: 16px;
          color: #ffffff;
          cursor: pointer;
          background: transparent;
          border-bottom: none;
          padding: 0;
          height: auto;
          line-height: normal;
          margin-right: 28px;

          &:hover {
            background: transparent;
            color: #ffffff;

            &::after {
              content: "";
              position: absolute;
              bottom: -16px;
              left: 50%;
              transform: translateX(-50%);
              width: 30px;
              height: 3px;
              background: #4f46e5;
            }
          }

          &.is-active {
            background: transparent;
            color: #ffffff !important;
            border-bottom: none;

            &::after {
              content: "";
              position: absolute;
              bottom: -16px;
              left: 50%;
              transform: translateX(-50%);
              width: 30px;
              height: 3px;
              background: #4f46e5;
            }
          }
        }
      }
    }

    .logo {
      font-weight: bold;
      font-size: 20px;
      color: #ffffff;
      display: flex;
      align-items: center;
      gap: 14px;
    }

    .pwd {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
      cursor: pointer;

      &:hover {
        opacity: 0.8;
      }
    }

    .username {
      display: flex;
      align-items: center;
      gap: 20px;
      font-size: 16px;
      color: #ffffff;

      .logout {
        width: 90px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        background: #4d83fd;
        border-radius: 15px;
        font-size: 14px;
        color: #ffffff;
        cursor: pointer;

        &:hover {
          background: #3a6ed6;
        }
      }
    }
  }

  .content {
    display: flex;
    margin-top: 80px;
    // width: 1200px;
    // margin: 0 auto;
    // height: calc(100vh - 50px);
    // overflow-x: hidden;

    .l-left {
      display: none;
      position: relative;
      min-width: 280px;
      width: 280px;
      overflow-y: auto;
      background: #eaf0fe;
      box-shadow: 0px 5px 24px 0px rgba(111, 135, 164, 0.49);
      padding: 38px 0;
      box-sizing: border-box;

      .nav-menu,
      .el-sub-menu {
        display: flex;
        flex-direction: column;
        gap: 15px;
        background: transparent;
        border-right: none;

        .el-sub-menu__title {
          padding: 0 20px;
          height: auto !important;
          line-height: normal !important;

          i {
            position: absolute;
            right: 40px;
            color: #4a4966;
          }

          &:hover i,
          &.is-active i {
            color: #ecf4ff;
          }
        }

        .el-menu-item,
        .el-sub-menu {
          width: 100%;
          background: #eaf0fe !important;

          .nav-item {
            width: 100%;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            height: 60px;
            padding-left: 20px;
            cursor: pointer;

            .nav-icon {
              width: 23px;
              display: flex;
              align-items: center;
              justify-content: center;
            }

            .nav-icon-active {
              width: 23px;
              display: flex;
              align-items: center;
              justify-content: center;
              display: none;
            }

            .nav-txt {
              display: flex;
              align-items: center;
              font-size: 16px;
              color: #4a4966;
              margin-left: 18px;
            }

            &.active,
            &:hover {
              background: #457aff;
              border-radius: 10px;

              .nav-txt {
                color: #ecf4ff;
              }

              .nav-icon {
                display: none;
              }

              .nav-icon-active {
                display: flex;
              }
            }
          }
        }

        .el-sub-menu {
          .el-menu {
            background: transparent !important;

            .el-menu-item {
              padding: 0 40px;
              height: auto !important;
              line-height: normal !important;

              .nav-item {
                position: relative;

                ::before {
                  content: "";
                  position: absolute;
                  left: 20px;
                  top: 50%;
                  transform: translateY(-50%);
                  width: 8px;
                  height: 8px;
                  border-radius: 50%;
                  background-color: #4a4966;
                }

                &.active {
                  border-radius: 10px;
                  background-color: #eaf0fe;

                  .nav-txt {
                    color: #457aff;
                  }

                  ::before {
                    background-color: #457aff;
                  }

                  .nav-icon-active {
                    display: flex;
                  }
                }

                &:hover {
                  background-color: #eaf0fe;

                  .nav-txt {
                    color: #457aff;
                  }

                  ::before {
                    background-color: #457aff;
                  }

                  .nav-icon {
                    display: none;
                  }

                  .nav-icon-active {
                    display: flex;
                  }
                }
              }
            }
          }
        }
      }
    }

    .l-right {
      // overflow-y: auto;
      flex: 1;
      // background: #f8fbff url("@/assets/img/right-bg.png") no-repeat 0 0;
      background: #f9fafb;
      background-size: 100%;
      padding: 30px 0px;
      box-sizing: border-box;
    }
  }
}
</style>
